import { resolve } from 'node:path'
import { defineConfig, loadEnv } from 'vite';
import Vue from '@vitejs/plugin-vue';
import Unocss from 'unocss/vite';
import pkg from './package.json';


export default defineConfig(({ mode }) => {
    const isProd = mode === 'production';

    let {
        VITE_APP_OUT_DIR,
        VITE_APP_API_URL,
        VITE_APP_PROXY_URL
    } = loadEnv(mode, process.cwd());

    VITE_APP_API_URL = VITE_APP_API_URL.startsWith('.') ? VITE_APP_API_URL.substring(1) : VITE_APP_API_URL;

    return {
        base: './',
        resolve: {
            alias: [
                { find: '@', replacement: resolve(__dirname, "src/") }
            ]
        },
        plugins: [
            Vue(),
            Unocss(),
        ],

        build: {
            outDir: VITE_APP_OUT_DIR,
            sourcemap: !isProd,
            rollupOptions: {
                output: {
                    chunkFileNames: 'js/[name]-[hash].js',
                    entryFileNames: 'js/[name]-[hash].js',
                    assetFileNames: '[ext]/[name]-[hash].[ext]',
                    manualChunks(id) {
                        if (id.includes('node_modules')) return 'vendor';
                    }
                },
            }
        },
        server: {
            port: 6173,
            host: '0.0.0.0',
            proxy: {
                [VITE_APP_API_URL]: {
                    target: VITE_APP_PROXY_URL,
                    changeOrigin: true,
                    rewrite: path => path.replace(new RegExp(`^${VITE_APP_API_URL}`), '')
                }
            }
        },
        define: {
            __APP_NAME__: JSON.stringify(pkg.name),
            __APP_VERSION__: JSON.stringify(pkg.version),
            __BUILD_TIME__: JSON.stringify(Date())
        }
    }
});